package com.sba.core.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sba.core.domain.Organization;
import com.sba.core.domain.User;
import com.sba.core.service.OrganizationService;
import com.sba.core.service.UserService;
import com.sba.core.util.StringUtil;
import com.sba.core.web.vo.ZTree;

/**
 * 
 * @author feiliming
 *
 */
@Controller
@RequestMapping("${ssh.admin-path}/organization")
public class OrganizationController extends BaseController {

	private final OrganizationService organizationService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	public OrganizationController(OrganizationService organizationService){
		this.organizationService = organizationService;
	}
	
	@GetMapping
	public String index(Map<String, Object> model){
		return adminThemePath + "/sys/organization";
	}
	
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public @ResponseBody JSONObject getOrganizations(Long parentId, String organizationType, String name, Integer limit, Integer offset){
		if(limit == null){
			limit = Integer.MAX_VALUE;
		}
		if(offset == null){
			offset = 0;
		}
		
		Page<Organization> page;
		//如果parentId和organizationType都传, 则只parentId有效
		if(parentId != null){
			if(StringUtil.isNotBlank(name)){
				page = organizationService.getOrganizationsByparentIdAndNameLike(parentId, name, limit, offset);
			}else{
				page = organizationService.getOrganizationsByParentId(parentId, limit, offset);
			}
		}else if(StringUtil.isNotBlank(organizationType)){
			if(StringUtil.isNotBlank(name)){
				page = organizationService.getOrganizationsByOrganizationTypeAndNameLike(organizationType, name, limit, offset);
			}else{
				page = organizationService.getOrganizationsByOrganizationType(organizationType, limit, offset);
			}
		}else{
			if(StringUtil.isNotBlank(name)){
				/**try {
					String dname = URLDecoder.decode(name, "UTF-8");
					name = dname;
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}*/
				page = organizationService.getOrganizationsByNameLike(name, limit, offset);
			}else{
				page = organizationService.getOrganizations(limit, offset);
			}
		}
		
		JSONObject obj = new JSONObject();
		obj.put("list", page.getContent());
		obj.put("total", page.getTotalElements());
		obj.put("totalPages", page.getTotalPages());
		return obj;
	}
	
	@RequestMapping(path = "/ztlist", method = RequestMethod.GET)
	public @ResponseBody List<ZTree> getOrganizationsForZTree(Long parentId, String organizationType, String name, Integer limit, Integer offset){
		if(limit == null){
			limit = Integer.MAX_VALUE;
		}
		if(offset == null){
			offset = 0;
		}
		
		Page<Organization> organizations;
		//如果parentId和organizationType都传, 则只parentId有效
		if(parentId != null){
			if(StringUtil.isNotBlank(name)){
				organizations = organizationService.getOrganizationsByparentIdAndNameLike(parentId, name, limit, offset);
			}else{
				organizations = organizationService.getOrganizationsByParentId(parentId, limit, offset);
			}
		}else if(StringUtil.isNotBlank(organizationType)){
			if(StringUtil.isNotBlank(name)){
				organizations = organizationService.getOrganizationsByOrganizationTypeAndNameLike(organizationType, name, limit, offset);
			}else{
				organizations = organizationService.getOrganizationsByOrganizationType(organizationType, limit, offset);
			}
		}else{
			if(StringUtil.isNotBlank(name)){
				organizations = organizationService.getOrganizationsByNameLike(name, limit, offset);
			}else{
				organizations = organizationService.getOrganizations(limit, offset);
			}
		}
		
		List<ZTree> ztOrganizations = new ArrayList<ZTree>();
		for(Organization r : organizations.getContent()) {
			ZTree zt = new ZTree();
			zt.setId(r.getId());
			zt.setpId(r.getParentId());
			zt.setName(r.getName());
			ztOrganizations.add(zt);
		}
		return ztOrganizations;
	}
	
	@PostMapping("/save")
	public @ResponseBody JSONObject saveOrganization(Organization organization){
		organization.setCreateTime(new Date());
		organization.setIsDelete(0);
		JSONObject obj = new JSONObject();
		try {
			organizationService.saveOrUpdate(organization);
			obj.put("success", true);
			obj.put("msg", "保存机构成功！");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "保存机构失败！");
		}
		return obj;
	}
	
	@GetMapping("/get")
	public @ResponseBody Organization getOrganization(Long id){
		return organizationService.getById(id);
	}
	
	@RequestMapping(path = "/delete", method = RequestMethod.POST)
	public @ResponseBody JSONObject deleteOrganization(Long id){
		Page<Organization> rp = organizationService.getOrganizationsByParentId(id, 1, 0);
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		if(rp.getTotalElements() > 0){
			obj.put("msg", "该机构下有子节点，禁止删除！");
			return obj;
		}else{
			Page<User> users = userService.getUsers(id, 1, 0);
			if(users.getTotalElements() > 0){
				obj.put("msg", "该机构下有用户，禁止删除！");
				return obj;
			}else{
				Organization organization = organizationService.getById(id);
				organization.setIsDelete(1);
				try {
					organizationService.saveOrUpdate(organization);
					obj.put("success", true);
					obj.put("msg", "删除机构成功！");
				} catch (Exception e) {
					obj.put("msg", "删除机构失败！");
				}
				return obj;
			}
		}
	}
	
}
